//
//  groupGuestViewController.m
//  QRMaster
//
//  Created by myApple on 15/10/12.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "groupGuestViewController.h"
#import "GuestModel.h"
#import "GuestManagerTableViewCell.h"
#import "groupInfoViewController.h"
#import "AppDelegate.h"
#import "UIView+MaterialDesign.h"
#import "addGroupGuestController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "checkPower.h"
#import "ZYPinYinSearch.h"
#import "ChineseInclude.h"
#import "GroupGuestLogic.h"
#import "BackBtn.h"
#import "ChineseString.h"
#import "pinyin.h"

@interface groupGuestViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UIActionSheetDelegate,UISearchDisplayDelegate>
{
    UIView  * titleView;
    NSMutableArray * allGuestInfoArray;
    UITableView * guestInfoTableView;
    NSMutableArray * guestInfoArray;
    UISearchBar * guestSearch;
    UISearchDisplayController * guestDisplayController;
    NSMutableArray * guestSearchData;
    NSMutableArray * memberArray;
    
    AppDelegate * newDelegate;
    
    //删除状态
    UIView * deleteView;
    UILabel * deleteCountLabel;
    NSMutableArray * deleteCellArray;
    
    UIButton * addBtn;    //添加组内客户
    
    BOOL isFirst;        //是否是第一次请求
    
    UILabel *titleLb;   //标题label
}

@end

@implementation groupGuestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isFirst = YES;
    guestInfoArray = [[NSMutableArray alloc]init];
    allGuestInfoArray = [[NSMutableArray alloc]init];
    memberArray = [[NSMutableArray alloc]init];
    deleteCellArray = [[NSMutableArray alloc]init];
    guestSearchData = [[NSMutableArray alloc]init];
    newDelegate = [UIApplication sharedApplication].delegate;
    [self prepareTableView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self prepareTitleView];
    addBtn.hidden  = NO;
    titleLb.hidden = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!guestDisplayController.isActive) {
        [self getDataFromSQLite];
    }
    [self getGeustInfoData];
//    if (YES == isFirst)
//    {
//        [self getGeustInfoData];
//        isFirst = NO;
//    }
    titleLb.text = NSLocalizedString(@"groupGuest", nil);
//    self.navigationItem.title = NSLocalizedString(@"groupGuest", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    addBtn.hidden = YES;
    deleteView.hidden = YES;
    titleLb.hidden = YES;
    [self clearDelete];
}

#pragma mark -- 判断是否从数据库获取数据

-(void)getDataFromSQLite
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    [groupGuestLogic queryGroupGuestInfo:_groupId block:^(NSMutableArray *groupGuestArray)
    {
        memberArray = groupGuestArray;
    }
    ];
        [allGuestInfoArray removeAllObjects];
        for (NSDictionary * dict in memberArray) {
                GuestModel * model = [[GuestModel alloc]init];
                model.guestid = [dict objectForKey:@"id"];
                model.headUrl = [dict objectForKey:@"headurl"];
                model.telePhone = [dict objectForKey:@"mobile"];
                model.email = [dict objectForKey:@"email"];
                model.guestName = [dict objectForKey:@"name"];
                model.sex = [dict objectForKey:@"gender"];
                model.isGroupManager = [dict objectForKey:@"isGroupManager"];
                model.firstChar = [dict objectForKey:@"firschar"];
                model.certificaties = [dict objectForKey:@"identity"];
            model.areaCode = [dict objectForKey:@"areaCode"];
            if ([model.isGroupManager isEqualToString:@"1"]) {
                [allGuestInfoArray insertObject:model atIndex:0];
            }
            else
            {
                 [allGuestInfoArray addObject:model];
            }
                _groupName = [memberArray[0] objectForKey:@"groupName"];
                [QRSingleton sharedQRSingleton].groupBeginTime = [memberArray[0] objectForKey:@"groupStartTime"];
                [QRSingleton sharedQRSingleton].groupEndTime = [memberArray[0] objectForKey:@"groupEndTime"];
        }
//    allGuestInfoArray=[self getChinesArray:allGuestInfoArray];
    
    //存放除组管理员外的客户（临时存储）
    NSArray *tempArray = [[NSArray alloc]init];
    //存放所有客户(临时存储)
    NSMutableArray *allTempArray = [[NSMutableArray alloc]init];
    if (allGuestInfoArray.count>=1)
    {
        tempArray = [allGuestInfoArray subarrayWithRange:NSMakeRange(1, allGuestInfoArray.count-1)];
        
    }
    tempArray = [self getChinesArray:tempArray];
    
    for (int i = 0; i<tempArray.count; i++)
    {
        [allTempArray addObject:[tempArray objectAtIndex:i]];
    }
    //处理特殊字符为＃
    for(int i = 0; i<allTempArray.count; i++)
    {
        ((GuestModel*)[allTempArray objectAtIndex:i]).firstChar=[self FirstCharToStr:((GuestModel *)[allTempArray objectAtIndex:i]).firstChar];
    }
    //首字母处理
    for(int i = 0; i<allTempArray.count; i++)
    {
        for(int j = i; j<allTempArray.count; j++)
        {
            if([((GuestModel *)[allTempArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[allTempArray objectAtIndex:j]).firstChar]==YES &&j!=i)
            {
                GuestModel * model = [[GuestModel alloc]init];
                model=[allTempArray objectAtIndex:j];
                model.firstChar=@"";
            }
        }
    }
    if (allGuestInfoArray.count > 0) {
        [allTempArray insertObject:[allGuestInfoArray objectAtIndex:0] atIndex:0];
    }
    allGuestInfoArray = allTempArray;
    guestInfoArray = [allGuestInfoArray mutableCopy];
    [guestInfoTableView reloadData];
}

-(void)prepareTitleView
{
    titleLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 44)];
    titleLb.backgroundColor = [UIColor clearColor];
    titleLb.textColor = [UIColor whiteColor];
    titleLb.font = [UIFont systemFontOfSize:18.0f];
    titleLb.textAlignment = NSTextAlignmentCenter;
    [self.navigationController.navigationBar addSubview:titleLb];
    
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 40;
    float y = 0;
    float width = 40;
    float height = 40;
    
    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(x, y, width, height);
    [addBtn addTarget:self action:@selector(addGuest) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:addBtn];
    
    UIImageView *addImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 30, 30)];
    UIImage * telePhoneImage = [UIImage imageNamed:@"ic_add30"];
    addImgView.image = telePhoneImage;
    [addBtn addSubview:addImgView];
    
    //删除状态下的导航栏
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = 44;
    deleteView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteView.backgroundColor =[UIColor blackColor];
    deleteView.userInteractionEnabled = YES;
    deleteView.hidden = YES;
    [self.navigationController.navigationBar addSubview:deleteView];
    
    //后退取消删除
    x = 0;
    y = 0;
    height = 40;
    width = 40;
    UIButton * clearDeleteBtn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"24x24"];
    [clearDeleteBtn addTarget:self action:@selector(clearDelete) forControlEvents:UIControlEventTouchUpInside];
    [deleteView addSubview:clearDeleteBtn];
    
    x = 40;
    y = 10;
    height = 20;
    width = 120;
    deleteCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteCountLabel.textColor = [UIColor whiteColor];
    deleteCountLabel.font = [UIFont systemFontOfSize:14.0];
    [deleteView addSubview:deleteCountLabel];
    
    //点击删除的按钮
    UIImageView * deleteImgView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 40, 5, 30, 30)];
//    deleteImgView.image = [UIImage imageNamed:@"ic_36_gabage"];
    deleteImgView.userInteractionEnabled = YES;
    [deleteView addSubview:deleteImgView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteCell:)];
    [deleteImgView addGestureRecognizer:tap];
    
    UIImageView *iconView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 20, 20)];
    iconView.image=[UIImage imageNamed:@"ic_36_gabage"];
    [deleteImgView addSubview:iconView];
    deleteImgView.backgroundColor=[UIColor clearColor];
}

-(void)createDeleteView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 20;
    float width = ScreenWidth;
    float height = 44;
    
    deleteView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteView.backgroundColor =[UIColor blackColor];
    deleteView.userInteractionEnabled = YES;
    deleteView.hidden = YES;
    [self.navigationController.navigationBar addSubview:deleteView];
    
    //后退取消删除
    x = 0;
    y = 0;
    height = 40;
    width = 40;
    UIButton * clearDeleteBtn = [BackBtn initWithFrame:CGRectMake(x, y, width, height) withImage:@"24x24"];
    [clearDeleteBtn addTarget:self action:@selector(clearDelete) forControlEvents:UIControlEventTouchUpInside];
    [deleteView addSubview:clearDeleteBtn];
    
    x = 40;
    y = 10;
    height = 20;
    width = 120;
    deleteCountLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    deleteCountLabel.textColor = [UIColor whiteColor];
    deleteCountLabel.font = [UIFont systemFontOfSize:14.0];
    [deleteView addSubview:deleteCountLabel];
    
    //点击删除的按钮
    UIImageView * deleteImgView = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth - 40, 5, 30, 30)];
    //    deleteImgView.image = [UIImage imageNamed:@"ic_36_gabage"];
    deleteImgView.userInteractionEnabled = YES;
    [deleteView addSubview:deleteImgView];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(deleteCell:)];
    [deleteImgView addGestureRecognizer:tap];
    
    UIImageView *iconView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 20, 20)];
    iconView.image=[UIImage imageNamed:@"ic_36_gabage"];
    [deleteImgView addSubview:iconView];
    deleteImgView.backgroundColor=[UIColor clearColor];
}
#pragma mark -- 取消删除状态
-(void)clearDelete
{
    [UIView animateWithDuration:0.5 animations:^{
        titleView.hidden = NO;
        deleteView.hidden = YES;
    } completion:^(BOOL finished) {
        [self clearDeleteStyle];
    }];
}

#pragma mark -- 取消删除时改变cell的状态
-(void)clearDeleteStyle
{
    for (NSIndexPath * cancelIndexPath in deleteCellArray) {
        UITableViewCell * cell = [guestInfoTableView cellForRowAtIndexPath:cancelIndexPath];
        cell.backgroundColor = [UIColor whiteColor];
    }
    [deleteCellArray removeAllObjects];
}

#pragma mark -- 准备删除
-(void)deleteCell:(UITapGestureRecognizer *)tap
{
    UIActionSheet * quitAcitonSheet = [[UIActionSheet alloc]initWithTitle:NSLocalizedString(@"sureDelete", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"not", nil) destructiveButtonTitle:NSLocalizedString(@"yes", nil) otherButtonTitles:nil];
    [quitAcitonSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        deleteView.hidden = YES;
        [self clearDelete];
       
    }
    else
    {
         [self makeSureDelete];
    }
}


#pragma mark -- 确认删除
-(void)makeSureDelete
{
    NSArray * sortArray = nil;
    if (deleteCellArray.count == 1) {
        sortArray = [deleteCellArray copy];
    }
    //排序
    else
    {
        sortArray = [deleteCellArray sortedArrayUsingComparator:^NSComparisonResult(NSIndexPath *obj1, NSIndexPath *obj2) {
            if (obj1.row > obj2.row) {
                return NSOrderedAscending;
            }
            else
            {
                return NSOrderedDescending;
            }
            
        }];
    }
    NSMutableString * memberIdString = [[NSMutableString alloc]init];
    //从大到小删除
    for (int i = 0; i < sortArray.count ; i ++) {
        NSInteger row = [[sortArray objectAtIndex:i]row];
        GuestModel * model = guestInfoArray[row];
        [memberIdString appendString:model.guestid];
        [memberIdString appendString:@","];
        [guestInfoArray removeObjectAtIndex:row];//删除数据源
    }
    [guestInfoTableView reloadData];
    [guestDisplayController.searchResultsTableView reloadData];
    /*
     删除 guesttableview 和 deleteguestcell 的顺序颠倒就会崩掉
     */
    @try {
        NSRange range;
        range.location = memberIdString.length - 1;
        range.length = 1;
        [memberIdString deleteCharactersInRange:range];
    }
    @catch (NSException *exception) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDicts = [[NSMutableDictionary alloc]init];
    __weak groupGuestViewController * weakSelf = self;
    [postDicts setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDicts setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDicts setValue:_communityId forKey:@"communityId"];
    [postDicts setValue: _groupId forKey:@"groupId"];
    [postDicts setValue: memberIdString forKey:@"clientId"];
   
    if([self getTimestamp:_groupId] != nil)
    {
        [postDicts setValue:[self getTimestamp:_groupId] forKey:@"timestamp"];
    }
    else
    {
        [postDicts setValue:@"" forKey:@"timestamp"];
    }

    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(DELETEGROUPCLIENT) params:postDicts block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if ([downLoadData objectForKey:@"cache"]) {
             if ([[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]integerValue] == 0)
             {
                 [self updateTimestamp:_groupId timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                 GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
                 [groupGuestLogic deleteGroupGuestInfo:_groupId groupGuest:memberIdString];
                 
             }
             else
             {
                 [weakSelf getGeustInfoData];
             }
         }
         if (error)
         {
             if ([[error objectForKey:@"status"]integerValue] == 334)
             {
                 [self getGeustInfoData];//用户在别处被删除了
             }
             [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
         }
         
     }
     ];
    
    [self clearDelete];
}

-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = 44;
    
    //搜索条的
    guestSearch = [[UISearchBar alloc]initWithFrame:CGRectMake(x, y, width, height)];
    guestSearch.placeholder = NSLocalizedString(@"accountOrName", nil);
    guestSearch.layer.masksToBounds = YES;
    guestSearch.keyboardType = UIKeyboardTypeNamePhonePad;
    guestSearch.delegate = self;
    guestDisplayController = [[UISearchDisplayController alloc]initWithSearchBar:guestSearch contentsController:self];
    guestDisplayController.searchResultsDataSource = self;
    guestDisplayController.searchResultsDelegate = self;
    guestDisplayController.delegate = self;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = ScreenHeight - y - 64;
    guestInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    guestInfoTableView.dataSource = self;
    guestInfoTableView.delegate = self;
    guestInfoTableView.tableFooterView = [[UIView alloc]init];
//    guestInfoTableView.tableHeaderView = guestSearch; 会造成mj的文字不显示
    [self.view addSubview:guestInfoTableView];
    [guestInfoTableView.mj_header beginRefreshing];
    guestInfoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
         [self getDataFromSQLite];
         [self getGeustInfoData];
    }];
    guestInfoTableView.tableHeaderView = guestSearch;
    //长按删除
    UILongPressGestureRecognizer * gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gestureLongPress:)];
    gestureLongPress.minimumPressDuration = 1.0;
    [guestInfoTableView addGestureRecognizer:gestureLongPress];
    
    UILongPressGestureRecognizer * gesturePress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gesturePress:)];
    gestureLongPress.minimumPressDuration = 1.0;
    [guestDisplayController.searchResultsTableView addGestureRecognizer:gesturePress];
    
}

-(void)getGeustInfoData
{
    if ([self IsHaveNetwork]) {
        [guestInfoTableView.mj_header endRefreshing];
        return;
    }
    
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_groupId forKey:@"groupId"];
    
    if([self getTimestamp:_groupId] != nil)
    {
        [postDict setValue:[self getTimestamp:_groupId] forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(GETGROUPCLIENTLIST) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if ([downLoadData objectForKey:@"cache"] != nil) {
             [self updateTimestamp:_groupId timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
             
             if ([[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]integerValue] == 1) {
                 NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
                 data = [downLoadData objectForKey:@"data"];
                 if (data) {

                     GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
                     [allGuestInfoArray removeAllObjects];
                     NSArray * guestArray = [data objectForKey:@"groupMembers"];
                     for (NSDictionary * dict in guestArray) {
                         GuestModel * model = [[GuestModel alloc]init];
                         model.guestid = [dict objectForKey:@"id"];
                         model.guestName = [dict objectForKey:@"name"];
                         model.sex = [dict objectForKey:@"gender"];
                         model.headUrl = [dict objectForKey:@"headurl"];
                         model.firstChar = [NSString stringWithFormat:@"%@",[dict objectForKey:@"firstchar"]];
                         model.telePhone = [dict objectForKey:@"mobile"];
                         model.email = [dict objectForKey:@"email"];
                         model.certificaties = [dict objectForKey:@"identity"];
                         model.isGroupManager = [dict objectForKey:@"isGroupManager"];
                         model.areaCode = [dict objectForKey:@"areaCode"];
                         [allGuestInfoArray addObject:model];
                     }
//                     allGuestInfoArray=[self getChinesArray:allGuestInfoArray];
                     
                      //存放除组管理员外的客户（临时存储）
                     NSArray *tempArray = [[NSArray alloc]init];
                      //存放所有客户(临时存储)
                     NSMutableArray *allTempArray = [[NSMutableArray alloc]init];
                     if (allGuestInfoArray.count>=1)
                     {
                         tempArray = [allGuestInfoArray subarrayWithRange:NSMakeRange(1, allGuestInfoArray.count-1)];
                         [allTempArray addObject:[allGuestInfoArray objectAtIndex:0]];
                     }
                     tempArray = [self getChinesArray:tempArray];
                     for (int i = 0; i<tempArray.count; i++)
                     {
                         [allTempArray addObject:[tempArray objectAtIndex:i]];
                     }
                     allGuestInfoArray = allTempArray;
                     
                     //处理特殊字符为＃
                     for(int i = 0; i<allGuestInfoArray.count; i++)
                     {
                         ((GuestModel*)[allGuestInfoArray objectAtIndex:i]).firstChar=[self FirstCharToStr:((GuestModel *)[allGuestInfoArray objectAtIndex:i]).firstChar];
                     }
                     
                     //首字母处理
                     for(int i = 0; i<allGuestInfoArray.count; i++)
                     {
                         for(int j = i; j<allGuestInfoArray.count; j++)
                         {
                             if([((GuestModel *)[allGuestInfoArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[allGuestInfoArray objectAtIndex:j]).firstChar]==YES &&j!=i)
                             {
                                 GuestModel * model = [[GuestModel alloc]init];
                                 model=[allGuestInfoArray objectAtIndex:j];
                                 model.firstChar=@"";
                             }
                         }
                     }
                     
                     guestInfoArray = [allGuestInfoArray mutableCopy];
                     NSDictionary * groupDict = [data objectForKey:@"groupInfo"];
                     _groupName = [groupDict objectForKey:@"groupName"];
                     [QRSingleton sharedQRSingleton].groupBeginTime = [groupDict objectForKey:@"groupStartTime"];
                     [QRSingleton sharedQRSingleton].groupEndTime = [groupDict objectForKey:@"groupEndTime"];
                      [groupGuestLogic deleteGroupGuestInfoByGroupId:_groupId];
                     for (NSMutableDictionary *dic in guestArray)
                     {
                         GuestModel *guestModel = [[GuestModel alloc]init];
                         guestModel.guestid =[dic objectForKey:@"id"];
                         guestModel.email =[dic objectForKey:@"email"];
                         guestModel.firstChar =[dic objectForKey:@"firstchar"];
                         guestModel.sex =[dic objectForKey:@"gender"];
                         guestModel.headUrl =[dic objectForKey:@"headurl"];
                         guestModel.certificaties =[dic objectForKey:@"identity"];
                         guestModel.isGroupManager =[dic objectForKey:@"isGroupManager"];
                         guestModel.telePhone =[dic objectForKey:@"mobile"];
                         guestModel.guestName =[dic objectForKey:@"name"];
                         guestModel.areaCode = [dic objectForKey:@"areaCode"];
                         [groupGuestLogic insertGroupGuestInfo:guestModel groupName:_groupName groupStartTime:[QRSingleton sharedQRSingleton].groupBeginTime  groupEndTime:[QRSingleton sharedQRSingleton].groupEndTime groupId:_groupId];
                     }
                 }
                 else
                 {
                     [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
                 }
             }
             [guestInfoTableView.mj_header endRefreshing];
             [guestInfoTableView reloadData];
             
         }
         
     }
     ];
}

#pragma mark -- 插入组客户数据到SQLite
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return guestInfoArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    GuestManagerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[GuestManagerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    for (NSIndexPath * selectIndexPath in deleteCellArray) {
        if (selectIndexPath.row == indexPath.row && selectIndexPath.section == indexPath.section) {
            cell.backgroundColor = RGBA(225, 225, 225, 1);
            break;
        }
    }
        if (guestInfoArray.count > indexPath.row) {
            GuestModel * model = guestInfoArray[indexPath.row];
//            cell.guestid = model.guestid;
            cell.guestName = model.guestName;
//            if (model.telePhone == nil || [@"" isEqualToString:model.telePhone] == YES)
//            {
//                cell.telePhone = model.email;
//            }
//            else
//            {
//                if ([model.areaCode isEqualToString:[QRSingleton sharedQRSingleton].currentAreaCodeString] || model.areaCode == nil || [model.areaCode isEqualToString:@""]) {
//                    cell.telePhone = model.telePhone;
//                }
//                else
//                {
//                    cell.telePhone = [NSString stringWithFormat:@"+%@ %@",model.areaCode,model.telePhone];
//                }
//            }
            cell.headUrl = model.headUrl;
//            cell.sex = model.sex;
//            cell.isGroupManager = model.isGroupManager;
//            cell.firstChar = model.firstChar;
//            cell.identityid = model.certificaties;
        }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (deleteCellArray.count > 0) {
        if (indexPath.row == 0) {
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerDelete", nil) superView:self.view];
            return;
        }
        for (NSIndexPath * deleteIndexPath in deleteCellArray) {
            if (indexPath.row == deleteIndexPath.row && indexPath.section == deleteIndexPath.section) {
               GuestManagerTableViewCell * cell = (GuestManagerTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                [cell mdDeflateAnimatedToPoint:CGPointMake(cell.frame.size.width /2.0, cell.frame.size.height / 2.0) backgroundColor:[UIColor whiteColor] duration:0.5 completion:nil];
                [deleteCellArray removeObject:indexPath];
                [self showDeleteView];
                if (deleteCellArray.count == 0) {
                    [self clearDelete];
                }
                return;
            }
        }
        if (indexPath == nil) {
            return;
        }
        GuestManagerTableViewCell * cell = (GuestManagerTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell mdInflateAnimatedFromPoint:CGPointMake(cell.frame.size.width /2.0, cell.frame.size.height / 2.0)  backgroundColor:RGBA(225, 225, 225, 1) duration:0.5 completion:nil];
        [deleteCellArray addObject:indexPath];
        [self showDeleteView];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak groupGuestViewController * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        [self stopWaiting];
        if ([data objectForKey:@"data"]!= nil) {
            NSArray * CommunityArray = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityArray) {
                if ([_communityId isEqualToString:[dict objectForKey:@"communityid"]]) {
                    NSString * managerRole = [dict objectForKey:@"role"];
                    groupInfoViewController * givc = [[groupInfoViewController alloc]init];
                    givc.groupName = weakSelf.groupName;
                    GuestModel * model = guestInfoArray[indexPath.row];
                    if ([model.isGroupManager isEqualToString:@"1"]) {
                        givc.isGroup = YES;
                    }
                    else
                    {
                        givc.isGroup = NO;
                    }
//                    if (indexPath.row == 0) {
//                        givc.isGroup = YES;
//                    }
//                    else
//                        givc.isGroup = NO;
                    givc.model = model;
                    givc.communityId = weakSelf.communityId;
                    givc.groupId = weakSelf.groupId;
                    givc.managerRole = managerRole;
                    if (guestDisplayController.isActive) {
                        [guestDisplayController setActive:NO animated:YES];
                    }
                    [self.navigationController pushViewController:givc animated:YES];
                    
                }
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    };
}

#pragma mark -- 长按进入删除模式
-(void)gestureLongPress:(UIGestureRecognizer *)longPress
{
    CGPoint tmPointTouch = [longPress locationInView:guestInfoTableView];
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self checkPower:tmPointTouch];
    }
}

#pragma mark ---- 删除时查看操作人的角色（超级管理员才可以删除）
-(void)checkPower:(CGPoint)touchPoint
{
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        [self stopWaiting];
        if ([data objectForKey:@"data"] != nil) {
            NSArray * CommunityArray = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityArray) {
                if ([_communityId isEqualToString:[dict objectForKey:@"communityid"]]) {
                    if ([[dict objectForKey:@"role"] isEqualToString:@"1"]) {
                        [self touchPoint:touchPoint InController:guestInfoTableView];
                        return ;
                    }
                }
            }
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerDelete", nil) superView:self.view];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
    };
}


#pragma mark -- 搜索出来的数据删除
-(void)gesturePress:(UIGestureRecognizer *)press
{
    CGPoint tmPointTouch = [press locationInView:guestDisplayController.searchResultsTableView];
    if (press.state == UIGestureRecognizerStateBegan) {
        [self touchPoint:tmPointTouch InController:guestDisplayController.searchResultsTableView];
    }
}

#pragma mark -- 长按触发删除
-(void)touchPoint:(CGPoint)point InController:(UITableView *)tableView
{
    NSIndexPath * NowPressIndexPath = [tableView indexPathForRowAtPoint:point];
    if (NowPressIndexPath.row == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"deleteGroup", nil) superView:self.view];
        return;
    }
    for (NSIndexPath * deleteIndexPath in deleteCellArray) {
        if (NowPressIndexPath.row == deleteIndexPath.row && NowPressIndexPath.section == deleteIndexPath.section) {
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:NowPressIndexPath];
            [cell mdDeflateAnimatedToPoint:CGPointMake(point.x, point.y - cell.frame.origin.y) backgroundColor:[UIColor whiteColor] duration:0.5 completion:nil];
            [deleteCellArray removeObject:NowPressIndexPath];
            [self showDeleteView];
            if (deleteCellArray.count == 0) {
                [self clearDelete];
            }
            return;
        }
    }
    if (NowPressIndexPath == nil) {
        return;
    }
    GuestManagerTableViewCell * cell = (GuestManagerTableViewCell *)[tableView cellForRowAtIndexPath:NowPressIndexPath];
    [cell mdInflateAnimatedFromPoint:CGPointMake(point.x, point.y - cell.frame.origin.y) backgroundColor:RGBA(225, 225, 225, 1) duration:0.5 completion:nil];
    [deleteCellArray addObject:NowPressIndexPath];
    [self showDeleteView];
}

-(void)showDeleteView
{
    deleteView.hidden = NO;
    titleView.hidden = YES;
    NSString * locaString = NSLocalizedString(@"havedChoose", nil);
    deleteCountLabel.text = [NSString stringWithFormat:@"%@%lu%@",locaString,(unsigned long)deleteCellArray.count,NSLocalizedString(@"people", nil)];
}

#pragma mark -- searchDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [guestInfoArray removeAllObjects];
    if (![ChineseInclude isIncludeChineseInString:searchText])
    {
        guestInfoArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:allGuestInfoArray andSearchText:searchText andSearchByPropertyName:@"guestName"]];
        for (GuestModel * model in allGuestInfoArray)
        {
            if (([model.telePhone rangeOfString:searchText].location != NSNotFound)||([model.email rangeOfString:searchText].location != NSNotFound)) {
                if([model.guestName rangeOfString:searchText].location == NSNotFound)
                {
                    [guestInfoArray addObject:model];
                }
            }
        }
    }
    else
    {
        for (GuestModel * model in allGuestInfoArray) {
            if (([model.guestName rangeOfString:searchText].location != NSNotFound)||([model.email rangeOfString:searchText].location != NSNotFound)) {
                [guestInfoArray addObject:model];
            }
        }
    }
    [guestInfoTableView reloadData];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    //如果是从删除模式跳转到搜索模式则去掉删除模式
    [self clearDelete];
    //修改取消的多语言
    searchBar.showsCancelButton = YES;
    for(id cc in [searchBar.subviews[0] subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:NSLocalizedString(@"alterCancel", nil) forState:UIControlStateNormal];
        }
    }
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    for (UIView * subView in guestDisplayController.searchResultsTableView.subviews)
    {
        if ([subView isKindOfClass:[UILabel class]]) {
            UILabel * label = (UILabel *)subView;
            label.text = NSLocalizedString(@"noSearch", nil);
        }
    }
    return YES;
}


#pragma mark -- cancleSearchbar
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
//    guestInfoArray = [allGuestInfoArray mutableCopy];
//    allGuestInfoArray=[self getChinesArray:allGuestInfoArray];
    //存放除组管理员外的客户（临时存储）
    NSArray *tempArray = [[NSArray alloc]init];
    //存放所有客户(临时存储)
    NSMutableArray *allTempArray = [[NSMutableArray alloc]init];
    if (allGuestInfoArray.count>=1)
    {
        tempArray = [allGuestInfoArray subarrayWithRange:NSMakeRange(1, allGuestInfoArray.count-1)];
        [allTempArray addObject:[allGuestInfoArray objectAtIndex:0]];
    }
    tempArray = [self getChinesArray:tempArray];
    
    for (int i = 0; i<tempArray.count; i++)
    {
        [allTempArray addObject:[tempArray objectAtIndex:i]];
    }
    allGuestInfoArray = allTempArray;
    guestInfoArray = [allGuestInfoArray mutableCopy];
    
    //处理特殊字符为＃
    for(int i = 0; i<allGuestInfoArray.count; i++)
    {
        ((GuestModel*)[allGuestInfoArray objectAtIndex:i]).firstChar=[self FirstCharToStr:((GuestModel *)[allGuestInfoArray objectAtIndex:i]).firstChar];
    }
    //首字母处理
    for(int i = 0; i<allGuestInfoArray.count; i++)
    {
        for(int j = i; j<allGuestInfoArray.count; j++)
        {
            if([((GuestModel *)[allGuestInfoArray objectAtIndex:i]).firstChar isEqualToString:((GuestModel *)[allGuestInfoArray objectAtIndex:j]).firstChar]==YES &&j!=i)
            {
                GuestModel * model = [[GuestModel alloc]init];
                model=[allGuestInfoArray objectAtIndex:j];
                model.firstChar=@"";
            }
        }
    }
    [guestInfoTableView reloadData];
    [self clearDelete];
}

-(void)addGuest
{
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    __weak groupGuestViewController * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        if ([data objectForKey:@"data"] != nil) {
            NSArray * CommunityData = [[data objectForKey:@"data"] objectForKey:@"communities"];
            for (NSDictionary * dict in CommunityData) {
                if ([_communityId isEqualToString:[dict objectForKey:@"communityid"]]) {
                    if (1 == [[dict objectForKey:@"role"]integerValue]) {
                        addGroupGuestController * aggc = [[addGroupGuestController alloc]init];
                        aggc.communityId = _communityId;
                        aggc.groupId = weakSelf.groupId;
                        aggc.groupName = _groupName;
                        [self.navigationController pushViewController:aggc animated:YES];
                        return;
                    }
                }
            }
            [PromptInfoView showMessage:NSLocalizedString(@"noPowerAddGroup", nil)];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    };
}

-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- 按照拼音排序
-(NSMutableArray*)getChinesArray:(NSArray*)arrToSort
{
    if (arrToSort.count == 0 || arrToSort == nil) {
        return nil;
    }
    //创建一个临时的变动数组
    int count = (int)arrToSort.count;
    for(int i =0; i < count; i++)
    {
        //创建一个临时的数据模型对象
        ChineseString *chineseString=[[ChineseString alloc]init];
        //给模型赋值
        GuestModel * model = [arrToSort objectAtIndex:i];
        NSString *pinYinResult = [NSString string];
        chineseString.string = model.guestName;
        if(chineseString.string==nil)
        {
            chineseString.string=@"";
        }
        if(![chineseString.string isEqualToString:@""])
        {
            //join(链接) the pinYin (letter字母) 链接到首字母
            char FirstHeader = pinyinFirstLetter([chineseString.string characterAtIndex:0]);
            if ((FirstHeader < 91 && FirstHeader > 64)||(FirstHeader < 123 && FirstHeader > 96)) {
                pinYinResult = [pinYinResult stringByAppendingString:[[NSString stringWithFormat:@"%c",FirstHeader]uppercaseString]];
            }else {
                pinYinResult = @"}";
            }
        }
        model.firstChar = pinYinResult;
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:[arrToSort sortedArrayUsingComparator:^NSComparisonResult(GuestModel * model1, GuestModel * model2) {
        return [model1.firstChar compare:model2.firstChar];
    }]];
    return array;
}


//通过groupId来查询到时间戳
-(NSString *)getTimestamp:(NSString *)groupId
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    return [groupGuestLogic queryGroupGuestTime:groupId];
}


//通过groupId来更新时间戳
-(void)updateTimestamp:(NSString *)groupId timeKeyValue:(NSString *)timeKeyValue
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    [groupGuestLogic updateGroupGuestTime:groupId keyValue:timeKeyValue];
}


@end
